package com.autoconfigure.redis.handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.Cache;
import org.springframework.cache.interceptor.CacheErrorHandler;

/**
 * @author lemon
 * @version 1.0
 * @description: 缓存异常处理
 * @date Create by lemon on 2020-07-08 11:08
 */
@Slf4j
public class DefaultCacheErrorHandler implements CacheErrorHandler {
    /**
     * Handle the given runtime exception thrown by the cache provider when
     * retrieving an item with the specified {@code key}, possibly
     * rethrowing it as a fatal exception.
     *
     * @param exception the exception thrown by the cache provider
     * @param cache     the cache
     * @param key       the key used to get the item
     * @see Cache#get(Object)
     */
    @Override
    public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) {
        this.doHandlerRedisErrorException(exception, key);
    }

    /**
     * Handle the given runtime exception thrown by the cache provider when
     * updating an item with the specified {@code key} and {@code value},
     * possibly rethrowing it as a fatal exception.
     *
     * @param exception the exception thrown by the cache provider
     * @param cache     the cache
     * @param key       the key used to update the item
     * @param value     the value to associate with the key
     * @see Cache#put(Object, Object)
     */
    @Override
    public void handleCachePutError(RuntimeException exception, Cache cache, Object key, Object value) {
        this.doHandlerRedisErrorException(exception, key);
    }

    /**
     * Handle the given runtime exception thrown by the cache provider when
     * clearing an item with the specified {@code key}, possibly rethrowing
     * it as a fatal exception.
     *
     * @param exception the exception thrown by the cache provider
     * @param cache     the cache
     * @param key       the key used to clear the item
     */
    @Override
    public void handleCacheEvictError(RuntimeException exception, Cache cache, Object key) {
        this.doHandlerRedisErrorException(exception, key);
    }

    /**
     * Handle the given runtime exception thrown by the cache provider when
     * clearing the specified {@link Cache}, possibly rethrowing it as a
     * fatal exception.
     *
     * @param exception the exception thrown by the cache provider
     * @param cache     the cache to clear
     */
    @Override
    public void handleCacheClearError(RuntimeException exception, Cache cache) {
        this.doHandlerRedisErrorException(exception, "清空缓存");
    }

    /**
     * @param exception
     * @param key
     * @return void
     * @description Redis 操作异常处理
     * @author lemon
     * @date 2020-07-08 12:40
     */
    protected void doHandlerRedisErrorException(Exception exception, Object key) {
        log.error(String.format("缓存 操作异常，key=[%s]", key), exception);
    }
}
